package com.stephen.utils.file;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by stephen on 2021-04-06 10:13 .
 * Description: 从路径中获取文件名
 */
public class GetFileName {

    public static void main(String[] args) {
        String path = "E:\\a\\b\\file.docx";
        // System.out.println(getFileNameBySplit(path));
        // System.out.println(getFileNameBySubString(null));
        // System.out.println(getFilePrefix(null));
        System.out.println(getFileSuffixBySubString("file.docx"));
        System.out.println(getFileSuffixBySplit("file.docx"));
    }
    // 1. split分割
    public static String getFileNameBySplit(String path) {
        if (StringUtils.isBlank(path)) {
            return null;
        }
        String[] split = path.split("\\\\");
        return split[split.length - 1];
    }

    // 2. substring截取
    public static String getFileNameBySubString(String path) {
        if (StringUtils.isBlank(path)) {
            return null;
        }
        return path.substring(path.lastIndexOf("\\") + 1);
    }


    // 获取文件名前缀
    public static String getFilePrefix(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        return fileName.substring(0,fileName.lastIndexOf("."));
    }

    // 获取文件名后缀: 1. 使用split
    public static String getFileSuffixBySplit(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        String[] split = fileName.split("\\.");
        return split[split.length - 1];
    }

    // 获取文件名后缀: 2. 使用substring
    public static String getFileSuffixBySubString(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }


}
